/*
 *
 * Copyright (C) 2008 Jose Javier García Zornoza.
 * 
 * Este es un programa libre; puedes distribuirlo y/o modificarlo bajo
 * los términos de la versión 2 (o cualquier versión posterior) de la Licencia 
 * Pública General de la Fundación de Software Libre.
 * Este programa se distribuye con la esperanza  de poder ser útil, pero sin
 * NINGUNA GARANTIA; tampoco la garantía implícita de COMERCIALIZACION o DEDICACIÓN
 * A UN PROPOSITO PARTICULAR. Ver la licencia GNU GPL para más detalles.
 * Deberías haber recibido una copia de la licencia GNU GPL con este programa;
 * en caso contrario puedes obtener una copia visitando el sitio web www.fsf.org
 * o escribiendo a la Fundación de Software Libre, Inc., 59 Temple 
 * Place - Suite 330, Boston, MA  02111-1307, USA. 
 *
 */
package org.gruposp2p.dnie.ui.panels;

import dniegp2pclient.DNIeGP2PClientApp;
import dniegp2pclient.RuntimeData;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.gruposp2p.dnie.cliente.rest.RestFacade;
import org.gruposp2p.dnie.model.DNIeSignedDocument;
import org.gruposp2p.dnie.model.SignedDocument;
import org.gruposp2p.dnie.ui.dialogs.ErrorDialog;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.Task;

public class ConnectToServerPanel extends javax.swing.JPanel {

    private static Logger logger = LoggerFactory.getLogger(ConnectToServerPanel.class);
    
    private ResourceMap resourceMap;
    private JFrame parentFrame;
    private SignedDocument signatureDocument;
    private JDialog parentDialog;

    /** Creates new form ConnectServerPanel */
    public ConnectToServerPanel() {
        initComponents();
        serverResponsePanel.setVisible(false);
    }

    public void setParentDialog (JDialog parentDialog) {
        this.parentDialog = parentDialog;
    }
    
    public void setTextFieldServidor (String rutaServidor) {
        urlServerTextField.setText(rutaServidor);
    }
    
    public void inicializarPaneles () {        
        serverDataPanel.setVisible(true);
        serverResponsePanel.setVisible(false);
        this.setVisible(true);
        getDocumentButton.setEnabled(true);
    }

    public JButton getDocumentGetButton () {
        return getDocumentButton;
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        serverDataPanel = new javax.swing.JPanel();
        urlServerLabel = new javax.swing.JLabel();
        urlServerTextField = new javax.swing.JTextField();
        getDocumentButton = new javax.swing.JButton();
        serverResponsePanel = new javax.swing.JPanel();
        responseLabel = new javax.swing.JLabel();
        acceptButton = new javax.swing.JButton();

        setName("Form"); // NOI18N

        serverDataPanel.setName("serverDataPanel"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance().getContext().getResourceMap(ConnectToServerPanel.class);
        urlServerLabel.setText(resourceMap.getString("urlServerLabel.text")); // NOI18N
        urlServerLabel.setName("urlServerLabel"); // NOI18N

        urlServerTextField.setName("urlServerTextField"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance().getContext().getActionMap(ConnectToServerPanel.class, this);
        getDocumentButton.setAction(actionMap.get("getDocumentToSign")); // NOI18N
        getDocumentButton.setIcon(resourceMap.getIcon("getDocumentButton.icon")); // NOI18N
        getDocumentButton.setText(resourceMap.getString("getDocumentButton.text")); // NOI18N
        getDocumentButton.setName("getDocumentButton"); // NOI18N

        javax.swing.GroupLayout serverDataPanelLayout = new javax.swing.GroupLayout(serverDataPanel);
        serverDataPanel.setLayout(serverDataPanelLayout);
        serverDataPanelLayout.setHorizontalGroup(
            serverDataPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, serverDataPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(urlServerLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(urlServerTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 341, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(getDocumentButton)
                .addContainerGap())
        );
        serverDataPanelLayout.setVerticalGroup(
            serverDataPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(serverDataPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(serverDataPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(urlServerLabel)
                    .addComponent(urlServerTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(getDocumentButton))
                .addContainerGap(15, Short.MAX_VALUE))
        );

        this.resourceMap = resourceMap;

        serverResponsePanel.setName("serverResponsePanel"); // NOI18N

        responseLabel.setFont(resourceMap.getFont("responseLabel.font")); // NOI18N
        responseLabel.setIcon(resourceMap.getIcon("responseLabel.icon")); // NOI18N
        responseLabel.setName("responseLabel"); // NOI18N

        acceptButton.setText(resourceMap.getString("acceptButton.text")); // NOI18N
        acceptButton.setName("acceptButton"); // NOI18N
        acceptButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                acceptButtonguardarReciboHandler(evt);
            }
        });

        javax.swing.GroupLayout serverResponsePanelLayout = new javax.swing.GroupLayout(serverResponsePanel);
        serverResponsePanel.setLayout(serverResponsePanelLayout);
        serverResponsePanelLayout.setHorizontalGroup(
            serverResponsePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, serverResponsePanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(responseLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 115, Short.MAX_VALUE)
                .addGap(300, 300, 300)
                .addComponent(acceptButton)
                .addContainerGap())
        );
        serverResponsePanelLayout.setVerticalGroup(
            serverResponsePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(responseLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 46, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, serverResponsePanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(acceptButton))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(serverDataPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(serverResponsePanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(serverDataPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(serverResponsePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void acceptButtonguardarReciboHandler(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_acceptButtonguardarReciboHandler
         JFileChooser chooser = new JFileChooser();
         chooser.showSaveDialog(parentFrame);
         File file = chooser.getSelectedFile();
         if (file!= null) {
             //FileUtils.guardar(respuestaServidor,file.getAbsolutePath(), "xml");
         }
    }//GEN-LAST:event_acceptButtonguardarReciboHandler

    @Action
    public Task getDocumentToSign() {
        String url = urlServerTextField.getText();
        if (url != null && !"".equals(url)) {
            urlServerTextField.setEnabled(false);
            return new GetDocumentToSignTask(
                    org.jdesktop.application.Application.getInstance(), url);
        } else {return null;}
    }

    private class GetDocumentToSignTask extends org.jdesktop.application.Task<Object, Void> {

        private String url = null;

        GetDocumentToSignTask(
                org.jdesktop.application.Application app, String url) {
            super(app);
            getDocumentButton.setEnabled(false);
            this.url = url;
            DNIeGP2PClientApp.getApplication().getView().setStatusMessageText(
                    resourceMap.getString("loadingDNIeDocumentToSign.text"));
        }
        @Override protected Object doInBackground() {
            SignedDocument signatureDocument = null;
            try {
                DNIeSignedDocument signedDocument = new DNIeSignedDocument();
                signedDocument.setDnieDocumentToSignId(
                        RestFacade.getDocumentToSign(url));
                signatureDocument = new SignedDocument (signedDocument);
            } catch (Exception exception) {
                DNIeGP2PClientApp.getApplication().getView().setStatusMessageText("");
                logger.error(exception.getMessage(), exception);
                ErrorDialog errorDialog = new ErrorDialog(
                        DNIeGP2PClientApp.getApplication().getView().getFrame(), true);
                errorDialog.setErrorMessage(exception.getMessage());
                getDocumentButton.setEnabled(true);
            }
            return signatureDocument;
        }
        @Override protected void succeeded(Object result) {
            DNIeGP2PClientApp.getApplication().getView().setStatusMessageText("");
            if (result != null) {
                signatureDocument = (SignedDocument)result;
                serverDataPanel.setVisible(false);
                acceptButton.setVisible(false);
                serverResponsePanel.setVisible(true);
                DNIeGP2PClientApp.getApplication().getView().setSignedDocument(
                        signatureDocument);
                RuntimeData.getInstance().isSignedDocumentLoaded = true;
                parentDialog.dispose();
                /*try {
                    SignatureValidator validator = new SignatureValidator ();
                    if (validator.validateSignature(
                        XmlUtils.getDocumentFromString(respuestaServidor, true), true)) {
                        botonGuardar.setVisible(true);
                        labelRespuestaEnvio.setIcon(resourceMap.getIcon(
                                "labelRespuestaEnvio.icon"));
                        labelRespuestaEnvio.setText(resourceMap.getString(
                                "labelRespuestaEnvioOK.text"));
                        serverDataPanel.setVisible(false);
                        serverResponsePanel.setVisible(true);
                    }
                } catch (Exception ex) {
                    logger.error(ex);
                }*/
            } else {
                urlServerTextField.setEnabled(true);
                serverResponsePanel.setVisible(true);
                getDocumentButton.setEnabled(true);
                responseLabel.setIcon(resourceMap.getIcon(
                        "labelRespuestaEnvioERROR.icon"));
                acceptButton.setVisible(false);
                parentDialog.dispose();
            }
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton acceptButton;
    private javax.swing.JButton getDocumentButton;
    private javax.swing.JLabel responseLabel;
    private javax.swing.JPanel serverDataPanel;
    private javax.swing.JPanel serverResponsePanel;
    private javax.swing.JLabel urlServerLabel;
    private javax.swing.JTextField urlServerTextField;
    // End of variables declaration//GEN-END:variables
    
}
